// index.ts
import { DiaryItem, getDiaryList } from '../../models/diary'
import { formatFullDateTime } from '../../utils/util'

// 获取应用实例
const app = getApp<IAppOption>()
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'

Page({
  data: {
    motto: 'Hello World',
    userInfo: {
      avatarUrl: defaultAvatarUrl,
      nickName: '',
    },
    hasUserInfo: false,
    canIUseGetUserProfile: wx.canIUse('getUserProfile'),
    canIUseNicknameComp: wx.canIUse('input.type.nickname'),
    diaryList: [] as DiaryItem[],
    showWeeklyReminder: false,
  },
  onLoad() {
    this.loadDiaryList()
    this.checkWeeklyReminder()
  },
  onShow() {
    // 页面显示时刷新数据
    this.loadDiaryList()
    this.checkWeeklyReminder()
  },
  // 事件处理函数
  bindViewTap() {
    wx.navigateTo({
      url: '../logs/logs',
    })
  },
  onChooseAvatar(e: any) {
    const { avatarUrl } = e.detail
    const { nickName } = this.data.userInfo
    this.setData({
      "userInfo.avatarUrl": avatarUrl,
      hasUserInfo: nickName && avatarUrl && avatarUrl !== defaultAvatarUrl,
    })
  },
  onInputChange(e: any) {
    const nickName = e.detail.value
    const { avatarUrl } = this.data.userInfo
    this.setData({
      "userInfo.nickName": nickName,
      hasUserInfo: nickName && avatarUrl && avatarUrl !== defaultAvatarUrl,
    })
  },
  getUserProfile() {
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log(res)
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    })
  },
  // 加载日记列表
  loadDiaryList() {
    const diaryList = getDiaryList()
    
    // 只显示最近的10条记录
    const recentDiaries = diaryList.slice(0, 10)
    
    this.setData({
      diaryList: recentDiaries
    })
  },
  
  // 检查是否应该显示周记提醒
  checkWeeklyReminder() {
    const diaryList = getDiaryList()
    
    // 获取本周的第一天（周一）
    const now = new Date()
    const dayOfWeek = now.getDay() || 7 // 将周日的0转为7
    const mondayOffset = 1 - dayOfWeek // 计算到本周一的偏移量
    const thisMonday = new Date(now)
    thisMonday.setDate(now.getDate() + mondayOffset)
    thisMonday.setHours(0, 0, 0, 0)
    
    // 检查是否有至少3条本周的日记
    const thisWeekDiaries = diaryList.filter(diary => 
      new Date(diary.timestamp).getTime() >= thisMonday.getTime()
    )
    
    this.setData({
      showWeeklyReminder: thisWeekDiaries.length >= 3
    })
  },
  
  // 跳转到写日记页面
  navigateToDiary() {
    wx.switchTab({
      url: '/pages/diary/diary'
    })
  },
  
  // 跳转到周记页面
  navigateToWeekly() {
    wx.switchTab({
      url: '/pages/weekly/weekly'
    })
  }
})
